package com.happysmile.srm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.happysmile.srm.config.NeedEnhance;
import com.happysmile.srm.mybatis.entity.Script;
import com.happysmile.srm.mybatis.entity.Script_tag;
import com.happysmile.srm.mybatis.entity.Tag;
import com.happysmile.srm.mybatis.mapper.ScriptMapper;
import com.happysmile.srm.mybatis.mapper.Script_tagMapper;
import com.happysmile.srm.mybatis.mapper.TagMapper;
import com.happysmile.srm.outter.R;
import com.sun.org.apache.xpath.internal.operations.Bool;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RestController
@SpringBootApplication
@RequestMapping("/srm")
@MapperScan("com.happysmile.srm.mybatis.mapper")
public class SrmApplication {

    public static void main(String[] args) {
        SpringApplication.run(SrmApplication.class, args);
    }





    @Resource
    private ScriptMapper scriptMapper;
    @Resource
    private TagMapper tagMapper;
    @Resource
    private Script_tagMapper script_tagMapper;

    @NeedEnhance(why = "1.从文件增加 2.批量增加脚本(脚本分割定界)",isAchieve = false,version = "1")
    @ApiOperation("录入单个脚本")
    @PostMapping("/add")
    public R add(@RequestBody @ApiParam("单个脚本")Script script){
        try {
            scriptMapper.insert(script);
        }catch (Exception e){
            return R.fail("脚本录入异常");
        }
        return R.success("脚本录入成功");
    }

    @ApiOperation("根据ids批量删除脚本,支持以,分隔")
    @GetMapping("/delete/{ids}")
    public R delete(String ids){
        List<Long> scriptIds = Stream.of(ids.split(",")).map(Long::valueOf).collect(Collectors.toList());
        if (scriptIds.isEmpty() || scriptIds == null)
            return R.fail("id不能为空!!!");
        try {
            return R.success(scriptMapper.deleteBatchIds(scriptIds));
        }catch (Exception e){
            return R.fail("删除失败!!!");
        }
    }

    /*
     * 根据id修改脚本内容，需要提供修改理由
     * */
    @ApiOperation("修改脚本内容，需要提供修改理由")
    @PostMapping("/update")
    public R update(@RequestBody Script script){
        try {
        scriptMapper.update(null,
                new UpdateWrapper<Script>()
                        .set("description",script.getDescription())
                        .set("content",script.getContent())
                        .set("is_more",script.getIsMore())
                        .set("modify_reason",script.getModify_reason())
                        .eq("id",script.getId()));
        }catch (Exception e){
            return R.fail();
        }
        return R.success("修改成功");
    }

    /*
     *  绑定脚本Id和tag
     * */
    @GetMapping("/bind/{scriptid}/{tag}")
    public R bindScriptIdandTag(@PathVariable @ApiParam("脚本Id") String scriptid,@PathVariable @ApiParam("标签") String tag){
        //1.如果tag不存在
        //1.1.插入tag
        if (!isExits(tag)){tagMapper.insert(Tag.builder().content(tag).createAt(new Date()).build());}
        //2.如果tag存在
        //2.1 往数据库中更新这个tag
        try {
            //2.1.1 .如果tag,id存在于中间表，则不重复插入
            if (isExits(tagMapper.selectOne(new QueryWrapper<Tag>().eq("content", tag)).getId(),
                    Long.valueOf(scriptid))) return R.fail("已存在这个标记，不可重复绑定!!!");
            script_tagMapper.insert(Script_tag.builder()
                    .scriptid(Long.valueOf(scriptid))
                    .tagid(tagMapper.selectOne(new QueryWrapper<Tag>().eq("content", tag)).getId()).build());
        }catch (Exception e){
            return R.fail("绑定失败!!!");
        }
        return R.success("绑定成功!!!");
    }

    /*
    * 根据tagid和scriptid查询数据库中是否存在
    * */
    @Transactional(rollbackFor = Exception.class)
    Boolean isExits(Long tagid,Long scriptid){
        Integer i = script_tagMapper.selectCount(
                new QueryWrapper<Script_tag>().eq("tagid",tagid).eq("scriptid",scriptid));
        if (i > 0){
            return Boolean.TRUE;
        }else {
            return Boolean.FALSE;
        }
    }

    /*
     * 根据tag内容查看tag是否存在
     * */
    @Transactional(rollbackFor = Exception.class)
    Boolean isExits(String tagContent){
        if (tagMapper.selectOne(new QueryWrapper<Tag>().eq("content", tagContent)) == null){
            return Boolean.FALSE;
        }else {
            return Boolean.TRUE;
        }
    }


    @ApiOperation("查询所有脚本内容")
    @GetMapping("/list")
    public R<List<Script>> query(){
        return R.success(scriptMapper.selectList(null));
    }

    /*
    * 根据id查询脚本是否存在
    * */
    @Transactional(rollbackFor = Exception.class)
    Boolean isExits(Long id){
        if (scriptMapper.selectOne(new QueryWrapper<Script>().eq("id",id)) == null){
            return Boolean.FALSE;
        }else {
            return Boolean.TRUE;
        }
    }





}
